<?php

namespace app\user\controller\mall\order;

use app\user\controller\mall\Base;
use think\Db;
use think\Exception;
use app\common\model\mall\oper\Notification;
use addons\mall\library\Service;
use app\common\model\mall\oper\Msgtpl;

/**
 * 商家订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Base
{
    
    /**
     * Orders模型对象
     * @var \app\common\model\mall\order\Order
     */
    protected $model = null;

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\mall\order\Order;
        $this->view->assign("delivertypeList", $this->model->getDelivertypeList());
        $this->view->assign("paytypeList", $this->model->getPaytypeList());
        $this->view->assign("ordersrcList", $this->model->getOrdersrcList());
        $this->view->assign("promTypeList", $this->model->getPromTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 商家订单
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,true,"o");
            $shop_id = cookie('shop_id');

            $total = $this->model->alias('o')
                ->join('__MALL_SHOP_SHOP__ s','o.shop_id=s.id','left')
                ->join('__MALL_ORDER_COMPLAIN__ oc','o.id=oc.order_id','left')
                ->join('__MALL_ORDER_REFUND__ orf','o.id=orf.order_id and orf.refundStatus!=-1','left')
                ->field('o.id,o.id order_id,o.shop_id,o.express_id,o.expressNo,o.orderRemarks,o.noticeDeliver,o.orderunique,o.orderNo,
                    o.goodsMoney,o.totalMoney,o.realTotalMoney,o.deliverType,o.deliverMoney,
		            o.payis,o.payType,o.payFrom,o.needPay,o.appraiseis,o.refundis,o.orderSrc,o.prom_type,
		            o.createtime,o.useScore,oc.id complainId,o.orderCode,o.status,orf.id refundId,s.name,s.shopQQ,s.shopWangWang')
                ->where("o.shop_id",$shop_id)
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model->alias('o')
                ->join('__MALL_SHOP_SHOP__ s','o.shop_id=s.id','left')
                ->join('__MALL_ORDER_COMPLAIN__ oc','o.id=oc.order_id','left')
                ->join('__MALL_ORDER_REFUND__ orf','o.id=orf.order_id and orf.refundStatus!=-1','left')
                ->field('o.id,o.id order_id,o.shop_id,o.express_id,o.expressNo,o.orderRemarks,o.noticeDeliver,o.orderunique,o.orderNo,
                    o.goodsMoney,o.totalMoney,o.realTotalMoney,o.deliverType,o.deliverMoney,
		            o.payis,o.payType,o.payFrom,o.needPay,o.appraiseis,o.refundis,o.orderSrc,o.prom_type,
		            o.createtime,o.useScore,oc.id complainId,o.orderCode,o.status,orf.id refundId,s.name,s.shopQQ,s.shopWangWang')
                ->where("o.shop_id",$shop_id)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            

            if(count($list)>0){
                $order_ids = [];
                foreach ($list as $v){
                    $order_ids[] = $v['order_id'];
                }
                $goods = db('mall_order_goods')->where('order_id','in',$order_ids)->select();
                $goodsMap = [];
                foreach ($goods as $v){
                    $v['goodsSpecNames'] = str_replace('@@_@@','、',$v['goodsSpecNames']);
                    $goodsMap[$v['order_id']][] = $v;
                }
                foreach ($list as $key => $v){
                    $list[$key]['allowRefund'] = 0;
                    //只要是已支付的，并且没有退款的，都可以申请退款操作
                    if($v['payType']==1 && $v['refundis']==0 && $v['refundId']=='' && ($v['payis'] ==1 || $v['useScore']>0)){
                        $list[$key]['allowRefund'] = 1;
                    }
                    //货到付款中使用了积分支付的也可以申请退款
                    if($v['payType']==0 && $v['useScore']>0 && $v['refundId']=='' && $v['refundis']==0){
                        $list[$key]['allowRefund'] = 1;
                    }
                    $list[$key]['list'] = $goodsMap[$v['order_id']];
                    $list[$key]['isComplain'] = 1;
                    if(($v['complainId']=='') && ($v['payType']==0 || ($v['payType']==1 && $v['status']!="unpay"))){
                        $list[$key]['isComplain'] = '';
                    }

                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();

    }

    /**
     * 修改价格
     */
    public function editmoney($ids = NULL){
        $row = $this->model->where('id',$ids)
            ->field('id,orderNo,goodsMoney,deliverMoney,useScore,scoreMoney,totalMoney,realTotalMoney')
            ->find();
        if (!$row)
            $this->error(__('No Results were found'));
        $userIds = $this->getDataLimitUserIds();
        if (is_array($userIds)) {
            if (!in_array($row[$this->dataLimitField], $userIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $this->modelSceneValidate ? $name . '.edit' : $name;
                        $result = $this->validate($params,$validate);
                        if(true !== $result){
                            // 验证失败 输出错误信息
                            $this->error($result);
                        }
                    }

                    $params["realTotalMoney"] = $params["newOrderMoney"];
                    $params["needPay"] = $params["newOrderMoney"];
                    $params["payRand"] = Db::raw("payRand+1");

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 商家发货
     */
    public function deliver($ids = NULL){
        $row = $this->model->where('id',$ids)
            ->field('id,user_id,orderNo,express_id,expressNo,userName,userPhone,area_ids,userAddress,orderRemarks,payType,payis,goodsMoney,deliverMoney,useScore,scoreMoney,totalMoney,realTotalMoney,needPay,status')
            ->find();
        if (!$row)
            $this->error(__('No Results were found'));
        $userIds = $this->getDataLimitUserIds();
        if (is_array($userIds)) {
            if (!in_array($row[$this->dataLimitField], $userIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = $this->modelSceneValidate ? $name . '.edit' : $name;
                    $result = $this->validate($params,$validate);
                    if(true !== $result){
                        // 验证失败 输出错误信息
                        $this->error($result);
                    }
                }
                Db::startTrans();
                try {
                    $params['status'] = "unreceive";
                    $params['deliveryTime'] = date('Y-m-d H:i:s');
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {

                        Db::commit();
                        $this->success();
                    } else {
                        Db::rollback();
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * 订单详情
     */
    public function detail($ids = NULL){
        if(!$ids)$ids=$this->request->param("ids");
        if ($this->request->isAjax()) {
            //获取订单商品
            $list = \app\common\model\mall\order\Goods::alias('og')
                ->join('__MALL_GOODS_GOODS__ g','og.goods_id=g.id','left')
                ->join('__MALL_SHOP_SHOP__ s','g.shop_id=s.id','left')
                ->where('order_id',$ids)
                ->field('og.*,og.goodsPrice*og.goodsNum subtotal,g.goodssn,g.goodsname,g.goodsimg,s.areaIds shopAreaIds,s.shopAddress,s.shopTel,s.name,s.shopQQ,s.shopWangWang')
                ->order('id asc')->select();

            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }
        $row = $this->model->detail($ids);
        if (!$row) $this->error(__('No Results were found'));
        $this->assign('row',$row);
        return $this->fetch();
    }

    /**
     * 订单打印
     */
    public function printf($ids = NULL){
        $row = $this->model->detail($ids);
        if (!$row) $this->error(__('No Results were found'));
        $this->assign('row',$row);

        //获取订单商品
        $list = Db::name('mall_order_goods')->alias('og')
            ->join('__MALL_GOODS_GOODS__ g','og.goods_id=g.id','left')
            ->join('__MALL_SHOP_SHOP__ s','g.shop_id=s.id','left')
            ->where('order_id',$ids)
            ->field('og.*,og.goodsPrice*og.goodsNum subtotal,g.goodsSn,s.areaIds shopAreaIds,s.shopAddress,s.shopTel,s.name,s.shopQQ,s.shopWangWang')
            ->order('id asc')->select();

        // 获取店铺地址
        foreach($list as $k=>$v){
            $areaNames = model('\app\common\model\mall\oper\Area')
                ->where("id","in",$v['shopAreaIds'])->column("name");
            $list[$k]['shopAddress'] = implode('',$areaNames).$v['shopAddress'];
        }
        $this->assign('list',$list);

        return $this->fetch();
    }

    /**
     *  获取未结算订单列表
     */
    public function unsettlement(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,false);
            $shop_id = cookie('shop_id');

            $total = $this->model
                ->field('id,orderNo,payType,goodsMoney,deliverMoney,totalMoney,
                    realTotalMoney,commissionFee,createtime,status')
                ->where(['shop_id'=>$shop_id,'status'=>['in','unappraise,finished'],'settlement_id'=>0])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->field('id,orderNo,payType,goodsMoney,deliverMoney,totalMoney,
                    realTotalMoney,commissionFee,createtime,status')
                ->where(['shop_id'=>$shop_id,'status'=>['in','unappraise,finished'],'settlement_id'=>0])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch("index");
    }
    /**
     * 获取已结算订单
     */
    public function settlemented(){

        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,true,"o");
            $shop_id = cookie('shop_id');

            $total = $this->model->alias('o')
                ->join('__MALL_SHOP_SETTLEMENT__ s','o.settlement_id=s.settlementId',"LEFT")
                ->field('o.id,o.orderNo,o.payType,o.goodsMoney,o.deliverMoney,
                    o.totalMoney,o.realTotalMoney,o.commissionFee,s.settlementTime,s.settlementNo')
                ->where(['o.shop_id'=>$shop_id,'o.status'=>['in','unappraise,finished'],'settlement_id'=>['>',0]])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model->alias('o')
                ->join('__MALL_SHOP_SETTLEMENT__ s','o.settlement_id=s.settlementId',"LEFT")
                ->field('o.id,o.orderNo,o.payType,o.goodsMoney,o.deliverMoney,
                    o.totalMoney,o.realTotalMoney,o.commissionFee,s.settlementTime,s.settlementNo')
                ->where(['o.shop_id'=>$shop_id,'o.status'=>['in','unappraise,finished'],'settlement_id'=>['>',0]])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch("index");

    }

    /**
     * 结算指定的订单
     */
    public function settlement($ids = NULL){
        $shopId = cookie('shop_id');
        $where['status'] = 'unappraise';
        $where['settlement_id'] = 0;
        $where['id'] = $ids;
        $where['shop_id'] = $shopId;
        $orders = $this->model->where($where)
            ->field('id,payType,realTotalMoney,lockCashMoney,scoreMoney,commissionFee')->select();
        if(empty($orders)) $this->error('没有需要结算的订单，请刷新后再核对!');
        $settlementMoney = 0;
        $commissionFee = 0;    //平台要收的佣金
        $ids = [];
        foreach ($orders as $key => $v) {
            $ids[] = $v['id'];
            if($v['payType']==1){//在线支付
                $settlementMoney += $v['realTotalMoney']+$v['scoreMoney'];
            }else{//货到付款
                $settlementMoney += $v['scoreMoney'];
            }
            $commissionFee += abs($v['commissionFee']);
        }

        $shops = model('Shop','model\mall\shop')->get($shopId);
        if(empty($shops)) $this->error('无效的店铺结算账号!');
        Db::startTrans();
        try{
            //$areaNames  = model('areas')->getParentNames($shops['bankAreaId']);
            $settlement = new \app\common\model\mall\shop\Settlement;
            $settlement->settlementType = 0;
            $settlement->shop_id = $shopId;
            $settlement->settlementMoney = $settlementMoney;
            $settlement->commissionFee = $commissionFee;
            $settlement->backMoney = $settlementMoney-$commissionFee;
            $settlement->settlementStatus = 0;
            //$settlement->createTime = date('Y-m-d H:i:s');
            $settlement->settlementNo =  '';
            $result = $settlement->save();
            if(false !==  $result){
                $settlement->settlementNo = $settlement->settlementId.(fmod($settlement->settlementId,7));
                $settlement->save();
                //修改订单关联的结算单ID
                $this->model->where('id','in',$ids)->update(['settlement_id'=>$settlement->settlementId]);
                //修改商家订单数据
                $commissionFee = -1*$commissionFee;//平台要收的佣金就等于商家要付的钱
                $shops->noSettledOrderNum = $shops->noSettledOrderNum-count($orders);
                $shops->paymentMoney = $shops->paymentMoney + $commissionFee;
                $shops->noSettledOrderFee = $shops->noSettledOrderFee-$commissionFee;
                $shops->save();
                Db::commit();
                $this->success('提交结算申请成功，请留意结算信息~');
            } else {
                Db::rollback();
                $this->error($settlement->getError());
            }
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->error('提交结算申请失败');
    }

}
